var api = require("../../api.js"),
    utils = require("../../utils.js"),
    images = require('../../utils/images.js'),
    app = getApp(),
    is_loading = !1,
    is_no_more = !1,
    QQMapWX = require("../../utils/qqmap-wx-jssdk.js");
  var qqmapsdk;
  var timer = 1;
  Page({
    data: {
      page: 1,
      page_count: 1,
      longitude: "112.97397",
      latitude: "28.094505",
      keyword: "",
      myAddress: '创谷软件园',
      shop_list: [],
      show_type: 0,
      tab: 1,
      sort: 1,
      miaosha: null,
      coupon_list: [],
      get_coupon_list: [],
      bargain: [],
      cat_id: 1,
      mch_id: null,
      banner_list: [],
      sortList: [{
          'image': images.nearbyShop.storeIcon,
          'title': '自营商家'
        },
        {
          'image': images.nearbyShop.nearbyshopIcon,
          'title': '附近商家'
        },
        {
          'image': images.nearbyShop.repastIcon,
          'title': '土特产直通'
        },
        {
          'image': images.nearbyShop.settledIcon,
          'title': '申请入驻'
        }
      ],
      curIndex: 0,
      scrollLeft: 0,
      swiperViewHeight: 1900,
      showGoodsSortView: false,
      goodsSortViewTop: 0,
      shopSortList: [],
      shop: {},
      curPage: 1,
      fixSegmentView: false,    // 用于标识商品分类条目视图是否固定在顶部
      segmentViewHeight: 0,     // 商品分类条目视图的高度
      searchIcon: images.common.searchSamllIcon,
      moreIcon: images.nearbyShop.moreIcon,
      moreUpIcon: images.nearbyShop.moreUpIcon,
      navigationIcon: images.nearbyShop.navigationIcon,
      qrCodeIcon: images.nearbyShop.qrCodeIcon,
      switchIcon: images.nearbyShop.switchIcon,
      locationSmallIcon: images.nearbyShop.locationSmallIcon,
      groupIcon: images.index.groupIcon,
      seckillIcon: images.index.seckillIcon
    },
    onLoad: function(res) {
      app.pageOnLoad(this);
      this.computedSwiperViewHeight()
      var a = this,
        e = res.user_id;
      qqmapsdk = new QQMapWX({
        key: 'XALBZ-UOZCI-PHQG7-5CBUT-JH6HQ-GWFES'
      });
      if (res.tab) {
        this.setData({
          tab: res.tab
        });
      }
      this.setData({
        show_type: 2
      });
      app.loginBindParent({
        parent_id: e
      }), wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success: function(res) {
                a.getMyLocation();
              }
            });
          } else {
            a.getMyLocation();
          }
        }
      });
    },
    onShow: function() {
      app.pageOnShow(this);
    },
    onPullDownRefresh: function() {
      this.setData({
        show_type: 2
      });
      var a = this;
      a.setData({
        keyword: "",
        page: 1,
        tab: 1,
        cat_id: 1,
        sort: 1,
      }), wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success: function(res) {
                a.getRefreshLocation();
              }
            });
          } else {
            a.getRefreshLocation();
          }
        }
      });
    },
    onReachBottom: function() {
      if (this.data.show_type == 2) {
        console.log('onReachBottom')
        this.getGoodsList();
      } else if (this.data.show_type == 1) {
        var t = this;
        t.data.page > t.data.page_count || t.loadMoreData();
      }
    },
    onPageScroll(event) {
      // 在页面滚动的过程中，判断商品条目视图是否需要固定在顶部
      const that = this
      let query = wx.createSelectorQuery()
      query.select('.goods-list').boundingClientRect(ref => {
        that.setData({
          fixSegmentView: ref && ref.top <= that.data.segmentViewHeight ? true : false
        })
      }).exec()
    },
    loadData: function() {
      if (this.data.show_type == 2) {
        this.getShopData();
        return;
      }
      // if (this.data.show_type != 1) {
      //   console.log(this.data.show_type);
      //   return;
      // }
    },
    loadMoreData: function() {
      var that = this,
        o = that.data.page;
      is_loading || (is_loading = !0, wx.showLoading({
        title: "加载中"
      }), app.request({
        url: api.mch.shop_lists,
        method: "GET",
        data: {
          cat_id: 0,
          page: o,
          lat: that.data.latitude,
          log: that.data.longitude,
          type: 1
        },
        success: function(t) {
          if (0 == t.code) {
            var a = that.data.shop_list.concat(t.data.list);
            that.setData({
              shop_list: a,
              page_count: t.data.PageCount,
              page: o + 1
            });
          }
        },
        complete: function() {
          wx.hideLoading(), is_loading = !1;
        }
      }));
    },
    /**
     * 根据当前经纬度获取附近的店
     */
    getShopData: function() {
      this.setData({
        current_page: 0
      });
      var a = this,
        o = (a.data.current_page || 0) + 1,
        e = "shop_data_mch_id_" + this.data.shop.id,
        t = wx.getStorageSync(e);
      t && a.setData({
        shop: t.shop
      }), wx.showNavigationBarLoading(), a.setData({
        loading: !0
      }), app.request({
        url: api.mch.shop_nearby_detail,
        data: {
          tab: a.data.tab,
          sort: a.data.sort,
          page: o,
          lat: a.data.latitude,
          log: a.data.longitude,
          cat_id: a.data.cat_id
        },
        success: function(t) {
          1 != t.code ? 0 == t.code && (a.setData({
              shop: t.data.shop,
              mch_id: t.data.shop.id,
              coupon_list: t.data.coupon_list,
              hot_list: t.data.goods_list,
              goods_list: t.data.goods_list,
              new_list: t.data.new_list,
              miaosha: t.data.miaosha,
              update_list: t.data.update_list,
              pintuan: t.data.pintuan,
              bargain: t.data.bargain,
              current_page: o
            }),
            // 获取店铺banner
            a.getBanner(),
            // 获取店铺分类数据
            a.loadStoreSortData(),
            wx.setStorageSync(e, t.data)) : wx.showModal({
            title: "提示",
            content: t.msg,
            showCancel: !1,
            success: function(t) {
              // t.confirm && wx.redirectTo({
              //   url: "../../mch/shop/shop"
              // })
            }
          });
          a.miaoshaTimer();
        },
        complete: function() {
          wx.hideNavigationBarLoading(), a.setData({
            loading: !1
          })
        }
      })
    },
    getGoodsList: function() {
      if (this.data.shopSortList.length === 0) {
        return
      }
      var a = this;
      const cat_id = this.data.cat_id
      const mch_id = this.data.shop.id
      if (3 != a.data.tab && !a.data.loading && !a.data.no_more) {
        a.setData({
          loading: !0
        });
        const page = (a.data.current_page || 0) + 1;
        console.log('page: ' + page)
        app.request({
          url: api.mch.shop,
          data: {
            mch_id: mch_id,
            tab: a.data.tab,
            sort: a.data.sort,
            page: page,
            cat_id: cat_id
          },
          success: function(t) {
            0 == t.code && (1 == a.data.tab && (t.data.goods_list && t.data.goods_list.length ? (a.data.hot_list = a.data.hot_list.concat(t.data.goods_list), a.setData({
                hot_list: a.data.hot_list,
                current_page: page
              })) : a.setData({
                no_more: !0
              })),
              2 == a.data.tab && (t.data.goods_list && t.data.goods_list.length ? (a.data.goods_list = a.data.goods_list.concat(t.data.goods_list), a.setData({
                goods_list: a.data.goods_list,
                current_page: page
              })) : a.setData({
                no_more: !0
              })))
              console.log('getGoodsList success')
          },
          complete: function() {
            console.log('goods_list')
            console.log(a.data.goods_list)
            a.setData({
              loading: !1
            })
          }
        })
      }
    },
    getRefreshLocation: function() {
      var a = this;
      wx.getLocation({
        success: function(res) {
          a.setData({
            longitude: res.longitude,
            latitude: res.latitude
          });
          // 将位置信息保存到本地
          wx.setStorageSync('location', res)
          a.reverseGeocoder(res.latitude, res.longitude)
        },
        complete: function() {
          a.loadData(), wx.stopPullDownRefresh();
        }
      });
    },
    // scrolltolower() {
    //   console.log('scrolltolower')
    //   console.log(this.data.show_type)
    //   if (this.data.show_type == 2) {
    //     console.log('getGoodsListgetGoodsList')
    //     this.getGoodsList();
    //   }
    // },
    inputFocus: function(t) {
      this.setData({
        show: !0
      });
    },
    inputBlur: function(t) {
      this.setData({
        show: !1
      });
    },
    inputConfirm: function(t) {
      this.onClickSearch()
    },
    inputChange: function(t) {
      this.setData({
        keyword: t.detail.value
      });
    },
    onClickSearch: function(t) {
      if (this.data.keyword) {
        // 前往搜索结果页面
        wx.navigateTo({
          url: '../search-shop/searchshop?keyword=' + this.data.keyword + '&latitude=' + this.data.latitude + '&longitude=' + this.data.longitude
        })
        // this.setData({
        //   show_type: 1
        // });
      } else {
        this.setData({
          show_type: 2
        });
      }
    },
    go: function(t) {
      var a = t.currentTarget.dataset.index,
        e = this.data.list;
      wx.navigateTo({
        url: "/pages/shop-detail/shop-detail?shop_id=" + e[a].id
      });
    },
    navigatorClick: function(t) {
      var a = t.currentTarget.dataset.open_type,
        e = t.currentTarget.dataset.url;
      return "wxapp" != a || ((e = function(t) {
          var a = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
            e = /^[^\?]+\?([\w\W]+)$/.exec(t),
            o = {};
          if (e && e[1])
            for (var n, i = e[1]; null != (n = a.exec(i));) o[n[1]] = n[2];
          return o;
        }(e)).path = e.path ? decodeURIComponent(e.path) : "", console.log("Open New App"),
        wx.navigateToMiniProgram({
          appId: e.appId,
          path: e.path,
          complete: function(t) {
            console.log(t);
          }
        }), !1);
    },
    onShareAppMessage: function(t) {
      return {
        path: "/pages/shop/shop?user_id=" + wx.getStorageSync("user_info").id
      };
    },
    miaoshaTimer: function() {
      var t = this;
      clearInterval(timer);
      t.data.miaosha && t.data.miaosha.rest_time && (timer = setInterval(function() {
        0 < t.data.miaosha.rest_time ? (t.data.miaosha.rest_time = t.data.miaosha.rest_time - 1,
          t.data.miaosha.times = t.getTimesBySecond(t.data.miaosha.rest_time), t.setData({
            miaosha: t.data.miaosha
          })) : clearInterval(timer);
      }, 1e3));
    },
    getTimesBySecond: function(t) {
      if (t = parseInt(t), isNaN(t)) return {
        h: "00",
        m: "00",
        s: "00"
      };
      var a = parseInt(t / 3600),
        e = parseInt(t % 3600 / 60),
        i = t % 60;
      return 1 <= a && (a -= 1), {
        h: a < 10 ? "0" + a : "" + a,
        m: e < 10 ? "0" + e : "" + e,
        s: i < 10 ? "0" + i : "" + i
      };
    },
    // 轮播图数据
    getBanner: function() {
      var that = this;
      app.request({
        url: api.mch.banner,
        data: {
          mch_id: this.data.mch_id,
        },
        success: function(d) {
          0 == d.code && that.setData({
            banner_list: d.data.banner_list[0],
          });
        },
        fail: function(res) {
        },
        complete: function() {
          that.computedSwiperViewHeight()
        }
      });
    },
    /**
     * 加载商铺分类数据 
     */
    loadStoreSortData() {
      const that = this;
      const path = "shop_cat_list_mch_id_" + this.data.shop.id,
        cacheData = wx.getStorageSync(path);
      const mch_id = that.data.shop.id
      cacheData && that.setData({
        shopSortList: cacheData
      }), wx.showNavigationBarLoading(), app.request({
        url: api.mch.shop_cat,
        data: {
          mch_id: mch_id
        },
        success: function(res) {
          0 == res.code && (that.setData({
              shopSortList: res.data.list,
              cat_id: res.data.list.length > 0 ? res.data.list[0].id : 0,
              current_page: 0,
              tab: 2,
              sort: 0,
              no_more: false,
              goods_list: []
            }),
            that.computedSegmentViewHeight(),
            // 加载第一个分类的数据
            that.getGoodsList(), wx.setStorageSync(path, res.data.list))
        },
        complete: function() {
          wx.hideNavigationBarLoading()
        }
      })
    },
    // 点击更多按钮，显示分类窗口
    onClickMoreButton() {
      // const that = this
      // var query = wx.createSelectorQuery()
      // query.select('.segment-view').boundingClientRect(function (res) {
      //     if (res) {
      //         let top = res.top 
      //         that.setData({
      //             goodsSortViewTop: top
      //         })
      //         console.log('top:' + top)
      //     }
      // })
      // query.exec(function (res) {})
      this.setData({
        showGoodsSortView: true
      })
    },
    // 隐藏分类窗口
    onClickSortItem(event) {
      const index = parseInt(event.target.dataset.index);
      if (index !== this.data.curIndex) {
        this.switchSegmentIndex(index)
      }
      this.setData({
        showGoodsSortView: false
      })
    },
    // 隐藏分类窗口
    onClickMaskView() {
      this.setData({
        showGoodsSortView: false
      })
    },
    // 修改商品导航index
    onSwitchSegment(event) {
      const index = parseInt(event.target.dataset.index);
      if (index !== this.data.curIndex) {
        this.switchSegmentIndex(index)
      }
    },
    // 切换商品类别
    switchSegmentIndex(index) {
      this.setData({
        curIndex: index,
        cat_id: this.data.shopSortList[index].id,
        current_page: 0,
        tab: 2,
        sort: 0,
        no_more: false,
        goods_list: []
      })
      this.getGoodsList()
      // 调整item的位置，显示当前选中的item
      const that = this
      if (index > 2) {
        var query = wx.createSelectorQuery()
        query.select('.scroll-segment-view').boundingClientRect(function(res) {
          if (res) {
            that.setData({
              scrollLeft: (index - 2) * 75
            })
          }
        })
        query.exec()
      } else {
        this.setData({
          scrollLeft: 0
        })
      }
    },
    // 获取用户当前位置
    getMyLocation: function() {
      var that = this;
      wx.getLocation({
        type: 'gcj02', // import!!!
        success: function(res) {
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude
          });
          that.reverseGeocoder(res.latitude, res.longitude)
        },
        complete: function(res) {
          that.loadData()
        }
      });
    },
    // 自营、附近、特产、申请入驻
    goMerchants(event) {
      const type = parseInt(event.currentTarget.dataset.type)
      if (type === 3) {
        wx.navigateTo({
          url: '/pages/admission/admission',
        })
        return
      } else if (type == 4) {
        this.goAdmission()
        return
      }
      wx.navigateTo({
        url: '/pages/merchants/merchants?cat_id=' + type + "&longitude=" + this.data.longitude + "&latitude=" + this.data.latitude,
      })
    },
    /**
     * 打开地图
     */
    goMapPage(event) {
      const that = this;
      const index = parseInt(event.currentTarget.dataset.index)
      wx.getSetting({
        success: function(res) {
          if (res.authSetting["scope.userLocation"]) {
            if (index === 0) {
              // 切换
              that.switchCurLocation()
            } else {
              // 打开当前店铺的地图页面
              that.openLocationPage()
            }
          } else {
            app.getauth({
              content: "需要获取您的地理位置授权，请到小程序设置中打开授权！",
              cancel: !1,
              success: function(authRes) {
                if (authRes.authSetting["scope.userLocation"]) {
                  if (index === 0) {
                    // 切换
                    that.switchCurLocation()
                  } else {
                    // 打开当前店铺的地图页面
                    that.openLocationPage()
                  }
                }
              }
            });
          }
        }
      });
    },
    /**
     * 打开二维码
     */
    goQrCode() {
      wx.navigateTo({
        url: `/mch/shop-qrcode/shop-qrcode?mch_id=${this.data.mch_id}`
      })
    },
    /**
     * 点击切换当前位置
     */
    switchCurLocation() {
      var that = this;
      console.log('indexindexindex')
      wx.chooseLocation({
        success: function(res) {
          console.log(res)
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude,
            cat_id: 1,
            keyword: "",
            show_type: 2,
            curIndex: 0,
            scrollLeft: 0
          });
          // 根据当前经纬度获取当前位置信息
          that.reverseGeocoder(res.latitude, res.longitude)
          // 根据当前经纬度重新获取附近的店
          that.getShopData()
        },
        fail: function(res) {
          wx.showToast({
            title: '选择位置失败'
          })
        }
      });
    },
    /**
     * 打开地图
     */
    openLocationPage() {
      const that = this
      wx.openLocation({
        latitude: parseFloat(that.data.shop.lat),
        longitude: parseFloat(that.data.shop.log),
        name: that.data.shop.name,
        address: that.data.shop.address
      });
    },
    /**
     * 大致计算SwiperViewHeight
     */
    computedSwiperViewHeight() {
      const windowHeight = wx.getSystemInfoSync().windowHeight
      const swiperViewHeight = windowHeight - 46 - 36 - 145 - 105 - 40 - 45 - 49 + 200
      console.log('swiperViewHeight: ' + swiperViewHeight)
      this.setData({
        swiperViewHeight: swiperViewHeight
      })
    },
    // 申请入驻
    goAdmission: function() {
      wx.showLoading({
        title: '加载中',
      }), app.request({
        url: api.mch.user.myshop,
        success: function(d) {
          if (d.code == -2) {
            wx.navigateTo({
              url: "/pages/admission/admission"
            });
          } else if (d.code == 0) {
            wx.navigateTo({
              url: "/pages/admission-result/admission-result?status=1"
            });
          } else if (d.code == -4) {
            wx.navigateTo({
              url: "/pages/admission-result/admission-result?status=2"
            });
          } else if (d.code == -3) {
            wx.navigateTo({
              url: "/pages/admission-result/admission-result?status=3"
            });
          }
        },
        fail: function(d) {
          wx.showToast({
            title: '申请入驻失败',
            image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
          });
        },
        complete: function(d) {
          wx.hideLoading();
        }
      });
    },
    /**
     * 根据经纬度获取推荐位置信息
     */
    reverseGeocoder(latitude, longitude, cb) {
      var that = this
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: function(addressRes) {
          var address = addressRes.result.formatted_addresses.recommend;
          that.setData({
            myAddress: address
          });
        },
        fail: function(res) {
          wx.showToast({
            title: '获取位置失败'
          });
        },
        complete: function() {
          cb && cb()
        }
      });
    },
    /**
     * 在获取分类数据后，计算segment view的高度
     */
    computedSegmentViewHeight() {
      const that = this
      let query = wx.createSelectorQuery()
      query.select('.segment-view').boundingClientRect(ref => {
        that.setData({
          segmentViewHeight: ref && ref.height 
        }) 
      }).exec()
    }
  });